package com.adn;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.interstitial.MediationCustomInterstitialLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener;
import com.qq.e.comm.util.AdError;
import com.santiao.publics.config.Const;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * YLH 插屏广告自定义Adapter
 */
public class GdtCustomerInterstitial extends MediationCustomInterstitialLoader {

    private static final String TAG = Const.TAG+GdtCustomerInterstitial.class.getSimpleName();

    private volatile UnifiedInterstitialAD mUnifiedInterstitialAD;
    private boolean isLoadSuccess;

    @Override
    public void load(Context context, AdSlot adSlot, MediationCustomServiceConfig serviceConfig) {
        /**
         * 在子线程中进行广告加载
         */
        ThreadUtils.runOnThreadPool(new Runnable() {
            @Override
            public void run() {
                if (context instanceof Activity) {
                    UnifiedInterstitialADListener unifiedInterstitialADListener = new UnifiedInterstitialADListener() {
                        @Override
                        public void onADReceive() {
                            isLoadSuccess = true;
                            Log.i(TAG, "GdtCustomerInterstitial--onADReceive");
                            if (isClientBidding()) { //bidding类型广告
                                double ecpm = mUnifiedInterstitialAD.getECPM();//当无权限调用该接口时，SDK会返回错误码-1
                                if (ecpm < 0) {
                                    ecpm = 0;
                                }
                                Log.e(TAG, "GdtCustomerInterstitial--ecpm:" + ecpm);
                                callLoadSuccess(ecpm);
                            } else {//普通类型广告
                                callLoadSuccess();
                            }
                        }

                        @Override
                        public void onVideoCached() {
                            Log.i(TAG, "GdtCustomerInterstitial--onVideoCached");
                        }

                        @Override
                        public void onNoAD(AdError adError) {
                            isLoadSuccess = false;
                            if (adError != null) {
                                Log.i(TAG, "GdtCustomerInterstitial--onNoAD errorCode = " + adError.getErrorCode() + " errorMessage = " + adError.getErrorMsg());
                                callLoadFail(adError.getErrorCode(), adError.getErrorMsg());
                            } else {
                                callLoadFail(40000, "no ad");
                            }
                        }

                        @Override
                        public void onADOpened() {
                            Log.i(TAG, "GdtCustomerInterstitial--onADOpened");
                            callInterstitialAdOpened();
                        }

                        @Override
                        public void onADExposure() {
                            Log.i(TAG, "GdtCustomerInterstitial--onADExposure");
                            callInterstitialShow();
                        }

                        @Override
                        public void onADClicked() {
                            Log.i(TAG, "GdtCustomerInterstitial--onADClicked");
                            callInterstitialAdClick();
                        }

                        @Override
                        public void onADLeftApplication() {
                            Log.i(TAG, "GdtCustomerInterstitial--onADLeftApplication");
                            callInterstitialAdLeftApplication();
                        }

                        @Override
                        public void onADClosed() {
                            Log.i(TAG, "GdtCustomerInterstitial--onADClosed");
                            callInterstitialClosed();
                        }

                        @Override
                        public void onRenderSuccess() {

                        }

                        @Override
                        public void onRenderFail() {

                        }
                    };
                    if (isServerBidding()) {
                        mUnifiedInterstitialAD = new UnifiedInterstitialAD((Activity) context, serviceConfig.getADNNetworkSlotId(), unifiedInterstitialADListener, null, getAdm());
                    } else {
                        mUnifiedInterstitialAD = new UnifiedInterstitialAD((Activity) context, serviceConfig.getADNNetworkSlotId(), unifiedInterstitialADListener);
                    }
                    mUnifiedInterstitialAD.loadAD();
                } else {
                    callLoadFail(40000, "GdtCustomerInterstitial--context is not Activity");
                }

            }
        });
    }

    @Override
    public void showAd(Activity activity) {
        Log.i(TAG, "自定义的showAd");
        /**
         * 先切子线程，再在子线程中切主线程进行广告展示
         */
        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                if (mUnifiedInterstitialAD != null) {
                    if (isServerBidding()) {
                        mUnifiedInterstitialAD.setBidECPM(mUnifiedInterstitialAD.getECPM());
                    }
                    mUnifiedInterstitialAD.show(activity);
                }
            }
        });

    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        /**
         * 在子线程中进行广告是否可用的判断
         */
        Future<MediationConstant.AdIsReadyStatus> future = ThreadUtils.runOnThreadPool(new Callable<MediationConstant.AdIsReadyStatus>() {
            @Override
            public MediationConstant.AdIsReadyStatus call() throws Exception {
                if (mUnifiedInterstitialAD != null && mUnifiedInterstitialAD.isValid()) {
                    return MediationConstant.AdIsReadyStatus.AD_IS_READY;
                } else {
                    return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
                }
            }
        });
        try {
            MediationConstant.AdIsReadyStatus result = future.get(500, TimeUnit.MILLISECONDS);//设置500毫秒的总超时，避免线程阻塞
            if (result != null) {
                return result;
            } else {
                return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "GdtCustomerInterstitial--onPause");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "GdtCustomerInterstitial--onResume");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "GdtCustomerInterstitial--onDestroy");

        /**
         * 在子线程中进行广告销毁
         */
        ThreadUtils.runOnThreadPool(new Runnable() {
            @Override
            public void run() {
                if (mUnifiedInterstitialAD != null) {
                    mUnifiedInterstitialAD.destroy();
                    mUnifiedInterstitialAD = null;
                }
            }
        });
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

    /**
     * 是否serverBidding广告
     *
     * @return
     */
    public boolean isServerBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_SERVER_BIDING;
    }
}
